package com.zhentao.file.service.Impl;

import com.zhentao.file.config.MinioConfig;
import com.zhentao.file.config.MinioConfigProperties;
import com.zhentao.file.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;

import java.io.InputStream;
import java.util.UUID;

@EnableConfigurationProperties(MinioConfigProperties.class)
@Import(MinioConfig.class)
public class FileStorageServiceImpl implements FileStorageService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfigProperties minioConfigProperties;

    //上传文件 以及  图片
    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) {

        try {
            //文件名的处理
            String name = UUID.randomUUID() + fileName;
            //文件的上传操作
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(name)
                    .contentType("text/html")
                    .bucket(minioConfigProperties.getBucket())
                    .stream(inputStream, inputStream.available(), -1)
                    .build();

            ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
            System.out.println("response: " + response.toString());

            //url
            String url = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
            System.out.println("url: " + url);

            return url;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //图片上传的方法
    @Override
    public String uploadImageFile(String fileName, InputStream inputStream) {

        try {
            String name = UUID.randomUUID() + fileName;
            //文件或图片进行上传到minio里面的操作
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(name)
                    .contentType("image/png")
                    .bucket(minioConfigProperties.getBucket())
                    .stream(inputStream, inputStream.available(), -1)
                    .build();

            ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
            System.out.println("response: " + response);
            //url
            String url = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
            System.out.println("url: " + url);

            return url;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
